<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.query.name" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="filter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="filter">搜索</el-button>
      <el-button v-permission="'/manage/role/add'" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleAddRole">添加</el-button>
    </div>

    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column prop="id" align="center" label="ID" width="95" sortable>
        <template v-slot="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" width="300">
        <template v-slot="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="角色描述">
        <template v-slot="scope">
          {{ scope.row.desc }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="170">
        <template v-slot="scope">
          <el-button v-permission="'/manage/role/update'" type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button v-permission="'/manage/role/delete'" :disabled="(scope.row.id === 1 || scope.row.id === 2)" type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="listQuery.totalRecords>0" :total="listQuery.totalRecords" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新建角色'" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="role" :rules="rules" label-position="right" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="role.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="role.desc"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="权限">
          <div id="treeDiv" style="overflow-y: scroll; height: 500px;">
            <el-tree
              ref="tree"
              :data="treeData"
              :default-checked-keys="defaultSelected"
              :props="props"
              :check-strictly="true"
              show-checkbox
              node-key="key"
              class="permission-tree"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <span>
                  <i v-if="data.isRoute" class="el-icon-menu" style="color: #67C23A;" />
                  <i v-else class="el-icon-cpu" />
                  {{ node.label }}
                </span>
                <span v-if="data.isRoute">
                  <el-tooltip v-if="!data.hidden" content="显示（hidden=false）" placement="top" :open-delay="500">
                    <svg-icon icon-class="eye-open" />
                  </el-tooltip>
                  <el-tooltip v-else content="隐藏（hidden=true）" placement="top" :open-delay="500">
                    <svg-icon icon-class="eye" />
                  </el-tooltip>
                </span>
              </span>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { getRolePermission, saveRolePermission, list as getRoles, add as addRole, del as deleteRole, update as updateRole } from '@/api/manage/role'
import { listTree } from '@/api/manage/route'
import Pagination from '@/components/Pagination'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  components: { Pagination },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      treeData: [],
      defaultSelected: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      props: { // tree 的 props 对象，用来映射新的 tree 属性
        label: 'name',
        children: 'children',
        isLeaf: 'leaf',
        key: 'id'
      },
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {
        }
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'change' },
          { max: 50, message: '角色名称 长度不能超过 50 个字符', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入项目名称', trigger: 'change' },
          { max: 50, message: '描述 长度不能超过 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
  },
  created() {
    this.fetchData()
  },
  methods: {
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    // tree：装载 tree 数据
    async loadTreeData() {
      const res = await listTree()
      this.treeData = res.data
    },
    fetchData() {
      this.listLoading = true
      getRoles(this.listQuery).then(response => {
        this.rolesList = response.data.list
        this.listQuery.totalRecords = response.data.page.totalRecords
        this.listLoading = false
      })
    },
    handleAddRole() {
      this.loadTreeData()
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.role = deepClone(scope.row)
      this.$nextTick(() => {
        this.loadTreeData()
        getRolePermission(scope.row.id).then(response => {
          this.defaultSelected = response.data
          this.$refs.tree.setCheckedNodes(this.defaultSelected)
        })
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认删除角色?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteRole(row.id)
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => { console.error(err) })
    },
    async confirmRole() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          const checkedKeys = this.$refs.tree.getCheckedKeys()
          if (isEdit) {
            await updateRole(this.role).then(() => {
              // 保存角色的所有权限
              saveRolePermission({
                roleId: this.role.id,
                permissions: checkedKeys
              })

              const index = this.rolesList.findIndex(v => v.id === this.role.id)
              this.rolesList.splice(index, 1, this.role)
              this.dialogVisible = false
              this.$message({ message: '修改成功!', type: 'success' })
            })
          } else {
            await addRole(this.role).then((response) => {
              // 保存角色的所有权限
              saveRolePermission({
                roleId: response.data.id,
                permissions: checkedKeys
              })

              this.dialogVisible = false
              this.$message({ message: '添加成功!', type: 'success' })
              this.fetchData()
            })
          }
        }
      })
    }
  }
}
</script>
